<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>生产报工登记</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 LeanCloud SDK -->
    <script src="https://cdn.jsdelivr.net/npm/leancloud-storage@4.13.2/dist/av-min.js"></script>
    <script src="https://cdn.sheetjs.com/xlsx-0.19.3/package/dist/xlsx.full.min.js"></script>
    
    <script>
        tailwind.config = {
            theme: {
                extend: { colors: { primary: '#2563EB', secondary: '#10B981', danger: '#EF4444', bg: '#F3F4F6' } }
            }
        }
    </script>
    <style>
        body { -webkit-tap-highlight-color: transparent; }
        input, select { font-size: 16px !important; }
        .card-shadow { box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); }
        .animate-fadeIn { animation: fadeIn 0.3s ease-out; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(-5px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body class="bg-bg text-gray-800 font-sans min-h-screen pb-24">

    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="px-4 py-3 flex justify-between items-center">
            <h1 class="font-bold text-lg text-primary"><i class="fa fa-industry"></i> 生产报工</h1>
            <button id="adminBtn" class="text-xs text-gray-400 border rounded px-2 py-1">管理员导出</button>
        </div>
    </header>

    <main class="p-4 max-w-md mx-auto space-y-4">
        
        <!-- 班组信息卡片 -->
        <div class="bg-white rounded-xl p-4 card-shadow">
            <div class="flex justify-between items-center mb-3 border-b pb-2">
                <h3 class="font-bold text-gray-700 flex items-center"><i class="fa fa-id-card-o text-primary mr-2"></i> 班组信息</h3>
                <span class="text-xs text-gray-400">自动记忆</span>
            </div>
            <div class="grid grid-cols-2 gap-3">
                <div class="col-span-2">
                    <label class="text-xs text-gray-500 block">日期</label>
                    <input type="date" id="date" class="w-full border rounded p-2 bg-gray-50">
                </div>
                <div><label class="text-xs text-gray-500">组别</label><input type="text" id="group" class="save-local w-full border rounded p-2" placeholder="如: 成品"></div>
                <div><label class="text-xs text-gray-500">小组</label><input type="text" id="team" class="save-local w-full border rounded p-2" placeholder="如: 开条"></div>
                <div class="col-span-2 flex gap-2">
                    <label class="flex-1 cursor-pointer"><input type="radio" name="shift" value="白班" class="save-local peer hidden"><div class="text-center py-2 border rounded peer-checked:bg-blue-50 peer-checked:text-primary border-gray-200">🌞 白班</div></label>
                    <label class="flex-1 cursor-pointer"><input type="radio" name="shift" value="夜班" class="save-local peer hidden"><div class="text-center py-2 border rounded peer-checked:bg-blue-900 peer-checked:text-white border-gray-200">🌙 夜班</div></label>
                </div>
            </div>
        </div>

        <!-- 任务详情卡片 -->
        <div class="bg-white rounded-xl p-4 card-shadow">
            <h3 class="font-bold text-gray-700 mb-3 border-b pb-2">任务详情</h3>
            <div class="space-y-3">
                <div><label class="text-xs text-gray-500">任务单号 *</label><input type="text" id="taskId" class="w-full border rounded p-2 uppercase" placeholder="输入单号"></div>
                <div><label class="text-xs text-gray-500">品名 *</label><input type="text" id="product" class="w-full border rounded p-2" placeholder="输入品名"></div>
                <div class="grid grid-cols-2 gap-3">
                    <div><label class="text-xs text-gray-500">数量</label><input type="number" id="quantity" class="w-full border rounded p-2" placeholder="0"></div>
                    <div><label class="text-xs text-gray-500">单基数</label><input type="number" id="unitBase" class="w-full border rounded p-2" placeholder="0"></div>
                </div>
            </div>
        </div>

        <!-- 出勤录入卡片 -->
        <div class="bg-white rounded-xl p-4 card-shadow border-l-4 border-secondary">
            <div class="flex justify-between items-center mb-3">
                <h3 class="font-bold text-gray-700">出勤录入</h3>
                <button id="addRowBtn" class="text-xs bg-green-50 text-green-600 px-2 py-1 rounded border border-green-200" type="button">+ 加一行</button>
            </div>
            <div id="attendanceList" class="space-y-2">
                <!-- 动态添加的出勤行会在这里 -->
            </div>
        </div>
    </main>

    <!-- 底部操作区 -->
    <div class="fixed bottom-0 left-0 right-0 bg-white border-t p-3 px-4 shadow-lg z-50 space-y-3">
        <button id="submitBtn" class="w-full bg-secondary text-white rounded-lg py-3 font-bold shadow-lg active:scale-95 transition-transform flex justify-center items-center" type="button">
            <i class="fa fa-cloud-upload mr-2"></i> 提交保存
        </button>
        
        <div id="adminPanel" class="hidden pt-2 border-t bg-gray-50 p-2 rounded">
            <div class="flex gap-2 items-center">
                <input type="password" id="adminPwd" placeholder="输入密码: 888" class="flex-1 border rounded px-2 py-1 text-sm">
                <button id="exportExcelBtn" class="bg-blue-600 text-white px-3 py-1 rounded text-sm font-bold whitespace-nowrap" type="button">
                    <i class="fa fa-download"></i> 下载Excel
                </button>
            </div>
            <p class="text-xs text-gray-400 mt-1 text-center">数据将从云端下载并自动转换为中文表头</p>
        </div>
    </div>

    <!-- 提示信息 -->
    <div id="toast" class="fixed top-4 left-1/2 transform -translate-x-1/2 bg-gray-800 text-white px-4 py-2 rounded-full shadow-xl hidden z-[100] text-sm flex items-center">
        <i id="toastIcon" class="fa fa-info-circle mr-2"></i> <span id="toastMsg"></span>
    </div>

    <script>
        // =======================================================
        // 🔴 LeanCloud 核心配置 - 已配置您的信息
        // =======================================================
        const LEANCLOUD_APP_ID = 'Jy6DXKgEGa0r1mZe1PtdmowS-gzGzoHsz';
        const LEANCLOUD_APP_KEY = 'orwbpOeN25iEa8MdaUxFRAFb';
        const LEANCLOUD_SERVER_URL = 'https://jy6dxkge.lc-cn-n1-shared.com';
        const EXPORT_PWD = '888';

        // 初始化 LeanCloud
        AV.init({
            appId: LEANCLOUD_APP_ID,
            appKey: LEANCLOUD_APP_KEY,
            serverURL: LEANCLOUD_SERVER_URL
        });

        // =======================================================
        // 🟢 应用初始化
        // =======================================================
        document.addEventListener('DOMContentLoaded', function() {
            initDate();
            loadCachedData();
            addAttendanceRow(true);
            bindEvents();
            console.log("生产报工系统初始化完成");
        });

        function bindEvents() {
            document.getElementById('addRowBtn').addEventListener('click', function() {
                addAttendanceRow();
            });
            document.getElementById('submitBtn').addEventListener('click', handleSubmit);
            document.getElementById('adminBtn').addEventListener('click', toggleAdmin);
            document.getElementById('exportExcelBtn').addEventListener('click', handleExport);
        }

        // 1. 基础功能
        function initDate() {
            const today = new Date();
            const formattedDate = today.toISOString().split('T')[0];
            document.getElementById('date').value = formattedDate;
        }

        function loadCachedData() {
            document.querySelectorAll('.save-local').forEach(input => {
                const val = localStorage.getItem('PROD_' + (input.id || input.name));
                if (val) {
                    if (input.type === 'radio') {
                        if (input.value === val) input.checked = true;
                    } else {
                        input.value = val;
                    }
                }
                input.addEventListener('change', e => localStorage.setItem('PROD_' + (e.target.id || e.target.name), e.target.value));
            });
        }
        
        function addAttendanceRow(isFirst = false) {
            const row = document.createElement('div');
            row.className = 'flex gap-2 items-center animate-fadeIn';
            row.innerHTML = `
                <input type="text" name="staffName" placeholder="姓名" class="flex-1 border rounded p-2 text-sm bg-gray-50 focus:bg-white" required>
                <input type="number" name="staffHours" placeholder="工时" class="w-20 border rounded p-2 text-sm bg-gray-50 focus:bg-white" min="0" step="0.5" required>
                ${!isFirst ? '<button type="button" onclick="this.parentElement.remove()" class="text-red-400 p-2"><i class="fa fa-minus-circle"></i></button>' : '<div class="w-8"></div>'}
            `;
            document.getElementById('attendanceList').appendChild(row);
        }

        // 2. 提交逻辑 - LeanCloud版本
        async function handleSubmit() {
            const taskId = document.getElementById('taskId').value.trim();
            const product = document.getElementById('product').value.trim();
            const group = document.getElementById('group').value.trim();
            
            if (!group || !taskId || !product) {
                return showToast('⚠️ 请完善必填信息 (组别/单号/品名)', true);
            }
            
            const staffRows = document.querySelectorAll('#attendanceList > div');
            let hasValidStaff = false;
            const staffData = [];
            
            staffRows.forEach(row => {
                const name = row.querySelector('input[name="staffName"]').value.trim();
                const hours = parseFloat(row.querySelector('input[name="staffHours"]').value);
                
                if (name && hours > 0) {
                    hasValidStaff = true;
                    staffData.push({ name, hours });
                }
            });
            
            if (!hasValidStaff) {
                return showToast('⚠️ 至少录入一个出勤人员及大于0的工时', true);
            }

            const btn = document.getElementById('submitBtn');
            const originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 提交中...';

            try {
                const commonData = {
                    date: document.getElementById('date').value,
                    zubie: group,
                    team: document.getElementById('team').value,
                    shift: document.querySelector('input[name="shift"]:checked')?.value,
                    taskId: taskId,
                    product: product,
                    quantity: Number(document.getElementById('quantity').value) || 0,
                    unitBase: Number(document.getElementById('unitBase').value) || 0
                };

                // LeanCloud 批量保存
                const savePromises = staffData.map(staff => {
                    const WorkLog = AV.Object.extend('WorkLog');
                    const log = new WorkLog();
                    
                    // 设置字段
                    log.set('date', commonData.date);
                    log.set('zubie', commonData.zubie);
                    log.set('team', commonData.team);
                    log.set('shift', commonData.shift);
                    log.set('taskId', commonData.taskId);
                    log.set('product', commonData.product);
                    log.set('quantity', commonData.quantity);
                    log.set('unitBase', commonData.unitBase);
                    log.set('staffName', staff.name);
                    log.set('staffHours', staff.hours);
                    
                    return log.save();
                });

                await Promise.all(savePromises);
                showToast('✅ 提交成功！数据已保存');
                
                // 清空表单
                document.getElementById('taskId').value = '';
                document.getElementById('product').value = '';
                document.getElementById('quantity').value = '';
                document.getElementById('unitBase').value = '';
                
                const list = document.getElementById('attendanceList');
                list.innerHTML = '';
                addAttendanceRow(true);

            } catch (e) {
                console.error("提交失败:", e);
                showToast(`❌ 提交失败: ${e.message || '请检查网络连接'}`, true);
            } finally {
                btn.disabled = false;
                btn.innerHTML = originalText;
            }
        }

        // 3. 导出逻辑 - LeanCloud版本
        function toggleAdmin() {
            const panel = document.getElementById('adminPanel');
            panel.classList.toggle('hidden');
            if(!panel.classList.contains('hidden')) {
                window.scrollTo(0, document.body.scrollHeight);
            }
        }

        async function handleExport() {
            const pwd = document.getElementById('adminPwd').value;
            if (pwd !== EXPORT_PWD) {
                return showToast('❌ 密码错误 (默认888)', true);
            }

            const btn = document.getElementById('exportExcelBtn');
            const oldText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '下载中...';

            try {
                const query = new AV.Query('WorkLog');
                query.descending('createdAt');
                query.limit(1000);
                const results = await query.find();

                if (!results || results.length === 0) {
                    throw new Error("没有数据可导出");
                }

                // 转换数据格式
                const excelData = results.map(item => ({
                    "提交时间": item.createdAt.toLocaleString(),
                    "日期": item.get('date'),
                    "组别": item.get('zubie'),
                    "小组": item.get('team'),
                    "班次": item.get('shift'),
                    "任务单号": item.get('taskId'),
                    "品名": item.get('product'),
                    "数量": item.get('quantity'),
                    "单基数": item.get('unitBase'),
                    "出勤人员": item.get('staffName'),
                    "工时": item.get('staffHours')
                }));

                const ws = XLSX.utils.json_to_sheet(excelData);
                const wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, "报工记录");
                
                const fileName = `生产报工_${new Date().toISOString().slice(0,10)}.xlsx`;
                XLSX.writeFile(wb, fileName);
                
                showToast('✅ Excel下载完成');

            } catch (e) {
                showToast(`❌ 导出失败: ${e.message}`, true);
            } finally {
                btn.disabled = false;
                btn.innerHTML = oldText;
            }
        }

        // 提示工具
        function showToast(msg, isError = false) {
            const t = document.getElementById('toast');
            const i = document.getElementById('toastIcon');
            document.getElementById('toastMsg').innerText = msg;
            
            t.classList.remove('bg-danger', 'bg-gray-800', 'hidden');

            if(isError) {
                t.classList.add('bg-danger');
                i.className = 'fa fa-times-circle mr-2';
            } else {
                t.classList.add('bg-gray-800');
                i.className = 'fa fa-check-circle mr-2';
            }
            
            t.classList.remove('hidden');
            setTimeout(() => t.classList.add('hidden'), 3000);
        }
    </script>
</body>
</html>